import useForm from "@module/useForm";
import Input from "@ui/RJMart/input";
import Icon from "@ui/RJMart/icons";
import RobinFilter from "@module/RobinFilter";
import ZenUI from "@root/components/ZenUI/ZenUI";
import usePartState from "@module/usePartState";

export default function StepThree(props) {
    const [stateObj, updateState] = usePartState({ canClickVerifyBtn: true });

    function doSubmit() {
        /*if (!formData.phone) {
            // alert("手机号码不能为空");
            updateFormData({
                $$status: { phone: "手机号码不能为空" }
            });
            return false;
        }*/

        if (!formData.code) {
            // alert("手机验证码不能为空");
            updateFormData({
                $$status: { code: "手机验证码不能为空" }
            });
            return false;
        }

        const isValid = formData.$$valid;
        if (isValid) {
            // ZenUI.SL(60);
            let pinUrl = "/store/api/user/es/approve/check/pin";
            let pinData = {
                code: formData.code
            };
            REST.post(pinUrl, pinData, "dis").then(
                function(data) {
                    // ZenUI.HL();
                    console.log(data);
                    if (data.code == "0000") {
                        doStepOne(data.token);
                    } else {
                        // alert(data.message);
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                },
                function(error) {
                    // ZenUI.HL();
                    console.log(error);
                }
            );
        }
    }

    function doStepOne() {
        $state.go({
            stateName: "/SignaturePwd",
            params: {
                step: 2
            }
        });
    }

    const {
        formData,
        handleChange,
        handleSubmit,
        updateFormData,
        validations,
        addValidate,
        addValidateMulti
    } = useForm(doSubmit, {}, "signFormStep1");

    React.useEffect(() => {
        getPhone();
    }, []);

    /*function phoneValidate(value) {
        let res = RobinFilter.phoneValidate(value);
        if (res) {
            updateState({ canClickVerifyBtn: false });
            return res;
        }
        updateState({ canClickVerifyBtn: true });
        return "";
    }*/

    addValidateMulti({
        // phone: [phoneValidate],
        code: [RobinFilter.verifyCodeValidate]
    });

    function beforeHandleChange(event) {
        handleChange(event);
        // console.log(formData)
    }

    function getPhone() {
        let phUrl = "/store/api/user/buyer/GetBuyer";
        let phData = {};
        REST.post(phUrl, phData, "noInfo").then(
            function(data) {
                console.log(data);
                if (data.code == "0000") {
                    let tmpPhone =
                        data.mobile.substr(0, 3) +
                        "****" +
                        data.mobile.substr(-4);
                    updateState({ phone: tmpPhone, realPhone: data.mobile });
                } else {
                    alert(data.message);
                }
            },
            function(error) {
                console.log(error);
            }
        );
    }

    return (
        <form
            className={"regi-content-form zen_p-b-80 zen_m-t-40"}
            name={"signFormStep1"}
        >
            {/*<InputItem
                name={"phone"}
                title={"手机号码"}
                placeholder={"用于账户验证，请务必正确填写"}
                handleChange={beforeHandleChange}
                formData={formData}
                updateFormData={updateFormData}
            />*/}
            <div className="regi-content-inputs">
                <div className="regi-step3-label-box">
                    <span className="regi-content-label">手机号码</span>
                </div>
                <div className="regi-inputs-input">
                    <div
                        name="phone"
                        className="h-input-root h-input-root-normal"
                    >
                        <div className="h-input-container">
                            <input
                                type="text"
                                className="h-input-input"
                                value={stateObj.phone}
                                name="phone"
                                disabled="disabled"
                            />
                        </div>
                    </div>
                </div>
            </div>

            <InputItemForVerifyCode
                name={"code"}
                title={"手机验证码"}
                placeholder={"请输入验证码"}
                handleChange={beforeHandleChange}
                phone={stateObj.realPhone}
                formData={formData}
                index={3}
                canClickVerifyBtn={stateObj.canClickVerifyBtn}
                updateFormData={updateFormData}
            />

            <NextStep doSubmit={doSubmit} formData={formData} />
        </form>
    );
}

function InputItem(props) {
    const {
        title,
        placeholder,
        index,
        handleChange,
        name,
        updateFormData
    } = props;
    let formData = props.formData;

    function addName() {
        let inputEle = document.querySelector(
            `.regi-inputs-input>div[name=${name}] input`
        );
        if (inputEle) {
            inputEle.setAttribute("name", name);
        }
    }

    React.useEffect(() => {
        addName();
    }, []);

    const isValid =
        formData.$$status.hasOwnProperty(name) && formData.$$status[name]
            ? false
            : true;

    return (
        <div className={"regi-content-inputs"}>
            <div
                className={
                    index == 3
                        ? "regi-step3-label-box2"
                        : "regi-step3-label-box"
                }
            >
                <span className={"regi-content-label"}>{title}</span>
            </div>
            <div className={"regi-inputs-input"}>
                <Input
                    name={name}
                    placeholder={placeholder}
                    onChange={handleChange}
                    error={!isValid}
                    statusIcon={
                        isValid ? null : (
                            <Icon
                                type="exclamation-circle-fill"
                                color="error"
                                width="18.26px"
                                height="18.26px"
                            />
                        )
                    }
                />

                {!isValid && (
                    <p className={"regi-content-error-tip"}>
                        {formData.$$status[name]}
                    </p>
                )}
            </div>
        </div>
    );
}

let unclickable = false;
function InputItemForVerifyCode(props) {
    const [stateObj, updateState] = usePartState({
        verifyTxt: "获取验证码",
        hasTimer: false
    });
    const {
        title,
        placeholder,
        index,
        handleChange,
        name,
        canClickVerifyBtn,
        updateFormData,
        phone
    } = props;
    let formData = props.formData;

    function addName() {
        let inputEle = document.querySelector(
            `.regi-inputs-input>div[name=${name}] input`
        );
        if (inputEle) {
            inputEle.setAttribute("name", name);
        }
    }

    React.useEffect(() => {
        addName();
    }, []);

    let timerId = null;
    function getVerifycode() {
        /*const isValid =
            formData.$$status.hasOwnProperty("phone") &&
            !formData.$$status["phone"]
                ? true
                : false;*/

        if (unclickable) {
            updateFormData({
                $$status: { code: "手机验证码请求太频繁，请稍后再试" }
            });
            return false;
        }

        if (props.phone) {
            let codeUrl = "/store/api/system/PinRequest";
            let codeData = {
                mobile: props.phone,
                useraction: "EsUserResetPassword"
            };
            REST.post(codeUrl, codeData, "dis").then(
                function(data) {
                    console.log(data);
                    if (data.code == "0000") {
                        console.log("获取验证码成功");
                        countDown(); //倒计时
                    } else if (data.code == "1012" || data.code == "1013") {
                        unclickable = true;
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    } else {
                        // alert(data.message);
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                },
                function(error) {
                    console.log(error);
                }
            );
        }
    }

    function countDown() {
        let seconds = 60;
        updateState({
            verifyTxt: `剩 ${seconds} 秒`,
            hasTimer: true
        });
        timerId = setInterval(() => {
            if (seconds <= 1) {
                updateState({
                    verifyTxt: `获取验证码`,
                    hasTimer: false
                });
                clearInterval(timerId);
                return;
            }
            seconds--;
            updateState({
                verifyTxt: `剩 ${seconds} 秒`,
                hasTimer: true
            });
        }, 1000);
    }

    const isValid =
        formData.$$status.hasOwnProperty(name) && formData.$$status[name]
            ? false
            : true;

    return (
        <div className={"regi-content-inputs"}>
            <div
                className={
                    index == 3
                        ? "regi-step3-label-box2"
                        : "regi-step3-label-box"
                }
            >
                <span className={"regi-content-label"}>{title}</span>
            </div>
            <div className={"regi-inputs-input"}>
                <Input
                    name={name}
                    placeholder={placeholder}
                    onChange={handleChange}
                    error={!isValid}
                    statusIcon={
                        isValid ? null : (
                            <Icon
                                type="exclamation-circle-fill"
                                color="error"
                                width="18.26px"
                                height="18.26px"
                            />
                        )
                    }
                />
                {canClickVerifyBtn ? (
                    <div
                        onClick={stateObj.hasTimer ? () => {} : getVerifycode}
                        className={
                            stateObj.hasTimer
                                ? "regi-step3-veri3"
                                : "regi-step3-veri2"
                        }
                    >
                        <p>{stateObj.verifyTxt}</p>
                    </div>
                ) : (
                    <div className={"regi-step3-veri"}>
                        <p>获取验证码</p>
                    </div>
                )}

                {!isValid && (
                    <p className={"regi-content-error-tip"}>
                        {formData.$$status[name]}
                    </p>
                )}
            </div>
        </div>
    );
}

function NextStep(props) {
    const { doSubmit, formData } = props;
    const isValid = formData.$$valid;
    return (
        <div
            onClick={doSubmit}
            className={
                isValid ? "regi-content-next-step" : "regi-content-next-step1"
            }
        >
            <p>下一步</p>
        </div>
    );
}
